package com.holly.exception;

import com.holly.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author holly
 * @create 2025-07-02 20:20
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handleException(Exception e){
        log.error("程序出错啦～",e);
        return Result.error("出错啦，请联系管理员！");
    }
    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        log.error("程序出错啦～",e);
        String message = e.getMessage();
        int i= message.indexOf("Duplicate entry");
        String errMsg = message.substring(i);
        String[] arr = errMsg.split( " ");
        return Result.error( arr[2]+" 已存在");
    }
    // 新增：处理自定义业务异常
    @ExceptionHandler(ServiceException.class)
    public Result handleServiceException(ServiceException e) {
        log.error("业务异常：{}", e.getMessage());
        return Result.error(e.getMessage()); // 直接返回异常中的信息
    }


}
